package com.jmb.waimao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jmb.waimao.entity.EmailTemplate;
import com.jmb.waimao.service.EmailTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * Controller for email template management
 */
@RestController
@RequestMapping("/api/email-templates")
@Slf4j
public class EmailTemplateController {

    @Autowired
    private EmailTemplateService emailTemplateService;

    /**
     * Create a new email template
     * 
     * @param template Email template to create
     * @return Created email template
     */
    @PostMapping
    public ResponseEntity<EmailTemplate> createTemplate(@RequestBody EmailTemplate template) {
        EmailTemplate createdTemplate = emailTemplateService.createTemplate(template);
        return ResponseEntity.ok(createdTemplate);
    }

    /**
     * Get all templates with pagination
     * 
     * @param page Page number
     * @param size Page size
     * @return Paged list of email templates
     */
    @GetMapping
    public ResponseEntity<Page<EmailTemplate>> getAllTemplates(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Page<EmailTemplate> pageRequest = new Page<>(page, size);
        LambdaQueryWrapper<EmailTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmailTemplate::getDeleted, 0)
                    .orderByDesc(EmailTemplate::getCreateTime);
        
        Page<EmailTemplate> result = emailTemplateService.page(pageRequest, queryWrapper);
        return ResponseEntity.ok(result);
    }

    /**
     * Get template by ID
     * 
     * @param id Template ID
     * @return Email template
     */
    @GetMapping("/{id}")
    public ResponseEntity<EmailTemplate> getTemplateById(@PathVariable Long id) {
        EmailTemplate template = emailTemplateService.getById(id);
        if (template != null && template.getDeleted() == 0) {
            return ResponseEntity.ok(template);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * Update a template
     * 
     * @param id Template ID
     * @param template Email template to update
     * @return Updated email template
     */
    @PutMapping("/{id}")
    public ResponseEntity<EmailTemplate> updateTemplate(
            @PathVariable Long id,
            @RequestBody EmailTemplate template) {
        
        EmailTemplate existingTemplate = emailTemplateService.getById(id);
        if (existingTemplate == null || existingTemplate.getDeleted() == 1) {
            return ResponseEntity.notFound().build();
        }
        
        template.setId(id);
        template.setUpdateTime(LocalDateTime.now());
        
        emailTemplateService.updateById(template);
        return ResponseEntity.ok(template);
    }

    /**
     * Delete a template
     * 
     * @param id Template ID
     * @return Success message
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteTemplate(@PathVariable Long id) {
        EmailTemplate template = emailTemplateService.getById(id);
        if (template != null) {
            template.setDeleted(1);
            template.setUpdateTime(LocalDateTime.now());
            emailTemplateService.updateById(template);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "Template deleted successfully");
            
            return ResponseEntity.ok(result);
        } else {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "Template not found");
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * Apply template variables
     * 
     * @param id Template ID
     * @param variables Variables to apply
     * @return Processed template
     */
    @PostMapping("/{id}/apply")
    public ResponseEntity<EmailTemplate> applyTemplateVariables(
            @PathVariable Long id,
            @RequestBody Map<String, String> variables) {
        
        try {
            EmailTemplate processedTemplate = emailTemplateService.applyTemplateVariables(id, variables);
            return ResponseEntity.ok(processedTemplate);
        } catch (Exception e) {
            log.error("Error applying template variables", e);
            return ResponseEntity.badRequest().build();
        }
    }
}
